package com.yejq.pansou;

import java.io.BufferedReader;
import java.io.FileReader;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.junit.Test;

import com.google.common.collect.Lists;

import us.codecraft.webmagic.downloader.HttpClientDownloader;
import us.codecraft.webmagic.selector.Html;

public class PanSouClient {
	
	private final static String BAIDU = "pan.baidu.com";
	
	public static void main(String[] args){
		/*String keyWord = null;
		if (args.length == 1) {
			keyWord = args[0];
		}else {
			System.out.println("usage: java -jar client keyWord");
		}
		if (StringUtils.isBlank(keyWord)) {
			return;
		}*/
		
		try {
			System.out.println("待处理：");
			List<String> keyWords = Lists.newArrayList();
			
			BufferedReader reader = new BufferedReader(new FileReader("noDown.txt"));
			String line = null;
			while((line = reader.readLine()) != null){
				if (StringUtils.isNotBlank(line)) {
					keyWords.add(line);
					System.out.println(line);
				}
			}
			reader.close();
			System.out.println("--------------------------------");
			
			for (String keyWord : keyWords) {
				search(keyWord);
				System.out.println("--------------------------------");
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Test
	public static void search(String keyWord) throws Exception{
		
		HttpClientDownloader downloader = new HttpClientDownloader();
		Html html = null;
		boolean done = false;
		int n = 0;
		while (!done) {
			try {
				html = downloader.download("http://www.pansou.com/s.php?q=" + keyWord);
			} catch (Exception e) {
				done = false;
				e.printStackTrace();
				Thread.sleep(2000);
			}
			if (html != null) {
				done = true;
			}
			n++;
			if (n>5) {
				break;
			}
		}
		
		//System.out.println(html.get());
		
		List<String> urls = html.xpath("//*[@id=\"result\"]/div/h2/a/@href").all();
		List<String> titles = html.xpath("//*[@id=\"result\"]/div/h2/a").all();
		
		for (int i = 0; i < titles.size(); i++) {
			System.out.println(HtmlUtils.delHTMLTag(titles.get(i)));
			//System.out.println(urls.get(i));
		}
		
		System.out.println("有百度网盘地址的链接：");
		Runtime runtime = Runtime.getRuntime();
		for (String url : urls) {
			html = null;
			done = false;
			n = 0;
			while (!done) {
				try {
					html = downloader.download(url);
				} catch (Exception e) {
					done = false;
					e.printStackTrace();
					Thread.sleep(2000);
				}
				if (html != null) {
					done = true;
				}
				n++;
				if (n>3) {
					break;
				}
			}
			if (html.get().indexOf(BAIDU) > -1) {
				System.out.println(url);
				runtime.exec("rundll32 url.dll,FileProtocolHandler " + url);
			}
		}
	}
	
	
}
